package com.rogerfan.easy.shiro;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.subject.WebSubject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.rogerfan.easy.model.hy.UserDto;
import com.rogerfan.easy.shiro.filter.AppUserNameToken;



public class ShiroUtils
{
	public static final String SESSION_KEY_YQ="session_key_yq";
	public static final String SESSION_KEY_DETAIL="SESSION_KEY_USER_DETAIL";
	
	public static final String SESSION_KEY_SOURCE="SESSION_KEY_SOURCE";

    
    
    /**
     * 判断是否有权限
     * 
     * @param role
     * @return
     */
    public static boolean hasRole(String role)
    {
        Subject currentUser = SecurityUtils.getSubject();
        return currentUser.hasRole(role);
    }
    /**
     * 取得用户的IP地址
     * 
     * @return
     */
    public static String getRequestIp(){
    	HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();  
    	return getIpAddr(request);
    	
    }

    /***
	 * 获取IP（如果是多级代理，则得到的是一串IP值）
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip != null && ip.length() > 0) {
			String[] ips = ip.split(",");
			for (int i = 0; i < ips.length; i++) {
				if (!"unknown".equalsIgnoreCase(ips[i])) {
					ip = ips[i];
					break;
				}
			}
		}
		return ip;
	}
	
	
	public static UserDto getUserFormPrincipal(String principal){
	
		UserDto vo=new UserDto();
		String[] name=principal.split("~~");
		vo.setId(Long.parseLong(name[0]));
		vo.setMobile(name[1]);
		return vo;
	}
	
	public static Long getUserId(){
		return getUserFormPrincipal(getSubject().getPrincipal().toString()).getId();
	}
	
	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}
	
	public static HttpServletRequest getRequest(){
		return (HttpServletRequest)((WebSubject)getSubject()).getServletRequest();
	}
	public static Session getSession(){
		return ((WebSubject)getSubject()).getSession();
	}
	
	public static AppUserNameToken getToken(){
		return (AppUserNameToken)getRequest().getAttribute(AppUserNameToken.REQUEST_TOKEN); 
	} 
}
